package com.czh.dao;

import org.apache.commons.dbcp.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class BaseDao {
    private static DataSource basicDataSourceFactory = null;
    static {
        try {
            InputStream resourceAsStream = BaseDao.class.getClassLoader().getResourceAsStream("DBCP.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);
            basicDataSourceFactory= BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static Connection getConnection() throws SQLException {
        return basicDataSourceFactory.getConnection();
    }
    //查询公共类
    public  static ResultSet getSelect(Connection con,PreparedStatement pre, ResultSet res, String sql, Object [] params) throws SQLException {
        pre = con.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            pre.setObject(i+1,params[i]);//setObject的参数从1开始！
        }
        res = pre.executeQuery();
        return res;
    }
    //更改公共类
    public static int  getUpdate(Connection con,PreparedStatement pre,String sql,Object [] params) throws SQLException {
        pre = con.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            pre.setObject(i+1,params[i]);
        }
        return pre.executeUpdate();
    }
    public static void closeConnect(Connection con, PreparedStatement pre, ResultSet res) throws SQLException {
        if(res !=null){
            res.close();
        }
        if (pre != null) {
            pre.close();
        }
        if (con != null) {
            con.close();
        }
    }
}
